package edu.drexel.cs575.taskManager.services.notification;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class notification_api {

	private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 465;
    private static final String SMTP_AUTH_USER = "notification.service.app@gmail.com";
    //note_ser_app
    private static final String SMTP_AUTH_PWD  = "notePASS";
	

	
	
	public Connection connect(){
		
		 Connection con = null; 
		try {  
		      Class.forName("com.mysql.jdbc.Driver").newInstance();  
		       
		      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/notifications",  
		        "root", "notasecret");  //   error is here **  error is here ***  error is here   
		  
		     	      
		      } catch(SQLException e) {  
		        
		        e.printStackTrace();  
		    }  
		    catch(Exception e) {  
		      System.err.println("Exception: " + e.getMessage());  
		    }   
		     
		return con;  
	}

	public void connectclose(Connection con){
	
		try {
		con.close();
		} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}

	}
	
	public boolean createNotification (String Appname, String Name, String Email, String Txt, String Social)
	{
		Statement stmt;
		String Appid = returnAppid(Appname);
		
		try {
		if (Appid.equals("")){
			Connection con = connect();
			String insert = "insert into InvokingApp (AppName) VALUE ('"+Appname+"')";
			stmt = con.createStatement();
	   		stmt.executeUpdate(insert);
	   		connectclose(con);
	   		Appid = returnAppid(Appname);
			
		}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		try{
		Connection con = connect();
		String insert2 = "insert into NotificationChannel values ("+Appid+",NULL,'"+Name+"','"+Email+"','"+Txt+"','"+Social+"')";
		System.out.println(insert2);
		stmt = con.createStatement();
   		stmt.executeUpdate(insert2);
   		connectclose(con);
   		return true;
		}
		catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return false;
		}
	}
	
	public boolean removeNotification (String Name, String Appname)
	{
		Statement stmt;
		String Appid = returnAppid(Appname);
		
		try{
			Connection con = connect();
			String insert2 = "DELETE from NotificationChannel where Appid_fk="+Appid+" AND Name='"+Name+"'";
			stmt = con.createStatement();
	   		stmt.executeUpdate(insert2);
	   		connectclose(con);
	   		return true;
			}
		catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
	}
	
	
	public boolean addNotificationPreference (String Username, String AppName, String Event_id, boolean Event_Pref){
		Statement stmt;
		String Appid = returnAppid(AppName);
		
		Statement stmt2;
		String uid=getUserNotifcation(Username, Appid);
		try{
			Connection con = connect();
			String insert2 = "insert into NotificatioN_Preferences values (NULL,'"+uid+"','"+Event_id+"',"+Event_Pref+")";
			System.out.println(insert2);
			stmt = con.createStatement();
	   		stmt.executeUpdate(insert2);
	   		connectclose(con);
	   		return true;
			}
			catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
			}
		

	}

	public String getEmail (String Name, String Appname)
	{
		Statement stmt;
		String Email="";
		String Appid = returnAppid(Appname);
		
		try{
			Connection con = connect();
			String select = "Select Email from NotificationChannel where Appid_fk="+Appid+" AND Name='"+Name+"'";
			stmt = con.createStatement();
	   		stmt.executeUpdate(select);
	   		
	   		ResultSet rs;
			rs = stmt.executeQuery(select);

			while (rs.next()) {
				  Email = rs.getString("Email");
				}
   		
	   		connectclose(con);
	   		return Email;
			}
		catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "";
			}
	}
	
	
	public String getTxt (String Name, String Appname)
	{
		Statement stmt;
		String Txt="";
		String Appid = returnAppid(Appname);
		
		try{
			Connection con = connect();
			String select = "Select Txt from NotificationChannel where Appid_fk="+Appid+" AND Name='"+Name+"'";
			stmt = con.createStatement();
	   		stmt.executeUpdate(select);
	   		
	   		ResultSet rs;
			rs = stmt.executeQuery(select);

			while (rs.next()) {
				  Txt = rs.getString("Email");
				}
   		
	   		connectclose(con);
	   		return Txt;
			}
		catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "";
			}
	}
	
	
	public String getSocial (String Name, String Appname)
	{
		Statement stmt;
		String Social="";
		String Appid = returnAppid(Appname);
		
		try{
			Connection con = connect();
			String select = "Select Social from NotificationChannel where Appid_fk="+Appid+" AND Name='"+Name+"'";
			stmt = con.createStatement();
	   		stmt.executeUpdate(select);
	   		
	   		ResultSet rs;
			rs = stmt.executeQuery(select);

			while (rs.next()) {
				  Social = rs.getString("Email");
				}
   		
	   		connectclose(con);
	   		return Social;
			}
		catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "";
			}
	}
	
	public String getNotificationPref (String Name, String AppName, String Event_id)
	{
		Statement stmt;
		String Appid = returnAppid(AppName);
		String uid=getUserNotifcation(Name, Appid);
		String Pref="";
		
		try{
			Connection con = connect();
			String select = "Select Event_Pref from Notification_Preferences where Userid_fk="+uid+" AND Event_id="+Event_id+"";
			stmt = con.createStatement();
	   		stmt.executeUpdate(select);
	   		
	   		ResultSet rs;
			rs = stmt.executeQuery(select);

			while (rs.next()) {
				  Pref = rs.getString("Email");
				}
   		
	   		connectclose(con);
	   		return Pref;
			}
		catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "";
			}
	}
	
	
	public boolean removeNotifcationPreference (String Username, String AppName, String Event_id ){
		
		String Appid = returnAppid(AppName);
		
		Statement stmt;
		String uid=getUserNotifcation(Username, Appid);
		
		try{
			Connection con = connect();
			String remove = "DELETE from Notification_Preferences where Userid_fk="+uid+" AND Event_id="+Username;
			stmt = con.createStatement();
	   		int rslt = stmt.executeUpdate(remove);
	   		connectclose(con);
	   		
	   		if (rslt == 1)
	   		return true;
	   		else
	   		return false;
		}
	   		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
			}
	}
	
	public void sendEmail(String email, String content, String Subject) throws AddressException, MessagingException{
		Properties props = new Properties();
		 
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", SMTP_HOST_NAME);
        props.put("mail.smtps.auth", "true");
        // props.put("mail.smtps.quitwait", "false");
 
        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();
 
        MimeMessage message = new MimeMessage(mailSession);
        // message subject
        message.setSubject(Subject);
        // message body
        message.setContent(content, "text/plain");
 
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(email));
 
        transport.connect
          (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
 
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }
	
	
	public void sendTxt(String phone, String carrier, String content) throws AddressException, MessagingException{
		
		
		String vendor = "";
		String txt="";
		vendor = carrier.toLowerCase();
		
		switch(vendor)
		{
		case "boost":txt=phone+"@myboostmobile.com"; break;
		case "tmobile":txt=phone+"@tmomail.net"; break;
		case "virgin":txt=phone+"@vmobl.net"; break;
		case "att":txt=phone+"@txt.att.net"; break;
		case "sprint":txt=phone+"@messaging.sprintpcs.com"; break;
		case "verizon":txt=phone+"@vtext.com"; break;
		default:txt="";
		}
		
		/*Boost Mobile: PhoneNumber@myboostmobile.com
		T-Mobile: PhoneNumber@tmomail.net
		Virgin Mobile: PhoneNumber@vmobl.com
		Cingular: PhoneNumber@cingularme.com
		Sprint Nextel: PhoneNumber@messaging.sprintpcs.com
		Verizon: PhoneNumber@vtext.com
		Nextel: PhoneNumber@messaging.nextel.com
		US Cellular: PhoneNumber@email.uscc.net
		SunCom: PhoneNumber@tms.suncom.com
		Powertel: PhoneNumber@ptel.net
		AT&T (Cingular): PhoneNumber@txt.att.net
		Alltel: PhoneNumber@message.alltel.com
		Metro PCS: PhoneNumber@MyMetroPcs.com*/
		
	
		Properties props = new Properties();
		 
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", SMTP_HOST_NAME);
        props.put("mail.smtps.auth", "true");
        // props.put("mail.smtps.quitwait", "false");
 
        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();
 
        MimeMessage message = new MimeMessage(mailSession);
        // message subject
        message.setSubject("Notification");
        // message body
        message.setContent(content, "text/plain");
 
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(txt));
 
        transport.connect
          (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
 
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }
	

	
	public void sendTweet(String useracct,String comment) throws TwitterException{
	
	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setDebugEnabled(true);
	cb.setOAuthConsumerKey("oCoXRtE2yNT9Pe6a1Y1Q");
	cb.setOAuthConsumerSecret("f4p102RkEFWonISYVXwTF8C7bsrb1Zdn8DUm2ArrR4");
	cb.setOAuthAccessToken("987863294-e75Vj8SfIhdZybbfTcZN6Sscs0AWg0hFLs7Fg1NY");
	cb.setOAuthAccessTokenSecret("tT14rSR4twYyUWPFLV7fNh2VE6laKDi6LtVHNE7o");
	TwitterFactory tf = new TwitterFactory(cb.build());
	Twitter twitter = tf.getInstance();
	
    twitter.updateStatus("@"+useracct+" Alert:"+comment);   
	}
	
	
	private String getUserNotifcation (String Name, String Appids){
		
		Connection con = connect();
		String select = "Select Groupid from Groupsrvc where GroupNm ='"+Appids+"'";
		String Appid="";
		try {
			
		Statement stmt = con.createStatement();
		ResultSet rs;
		rs = stmt.executeQuery(select);
				
		while (rs.next()) {
			  Appid = rs.getString("Groupid");
			}
		
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		
		connectclose(con);
		return Appid;
	}
	
	private String returnAppid (String Appname){
		
		Connection con = connect();
		String select = "Select Appid from InvokingApp where AppName ='"+Appname+"'";
		String Appid="";
		
		try {
			
		Statement stmt = con.createStatement();
		ResultSet rs;
		rs = stmt.executeQuery(select);
				
		while (rs.next()) {
			  Appid = rs.getString("Appid");
			}
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		connectclose(con);
		return Appid;
	}
}
	
	
